// import schema
const { LawItem } = require("../../schema/lawSchema");

/**
 * 通过id获取对应的子节点
 * @param {*} node
 * @param {*} queue
 */
async function getChildNode(node, queue, rootObj, lawTree) {
  for (let child of node.children) {
    // eslint-disable-next-line no-await-in-loop
    const childNode = await LawItem.findById(child);
    const copyNode = childNode.toObject();
    queue.push(copyNode);
    if (rootObj.isRoot) {
      lawTree.push(copyNode);
    } else {
      if (!node[childNode.type]) {
        node[childNode.type] = [];
      }
      node[childNode.type].push(copyNode);
    }
  }
  rootObj.isRoot = false;
}

/**
 * 从提供的根节点开始遍历源法律树，并创建对应的新法律树
 * @param {object} node - 传入法律的任意节点作为数据源
 * @return {Object} lawTree
 */
async function createNewTree(root) {
  const queue = [];
  const rootObj = { isRoot: true, count: 1 };
  const copyNode = root.toObject();
  const lawTree = { ...copyNode };
  const childNode = await LawItem.findById(lawTree.children[0].toString());
  lawTree[childNode.type] = [];
  await getChildNode(copyNode, queue, rootObj, lawTree[childNode.type]);
  while (queue.length > 0) {
    const currentNode = queue.shift();
    // eslint-disable-next-line no-await-in-loop
    await getChildNode(currentNode, queue, rootObj, lawTree);
  }
  return lawTree;
}

/**
 * 前序遍历法律数据
 * @param {*} node 递归节点
 * @param {*} arr 增添数组
 */
async function preOrderTraversal(nodeId, arr) {
  if (!nodeId) {
    return;
  }
  const node = await LawItem.findById(nodeId.toString());
  arr.push(node);
  for (let childId of node.children) {
    // eslint-disable-next-line no-await-in-loop
    await preOrderTraversal(childId, arr);
  }
}

module.exports = {
  createNewTree,
  preOrderTraversal,
};
